<template>
  <div class="user">
    <!-- 上半部分 -->
    <el-card class="box-card">
      <div class="box-content">
        <div class="content-left">
          <span style="margin:0 8px;font-size:14px;">用户名：</span>
          <el-input v-model="userName" type="text" placeholder="请输入用户名" style="width:180px;"></el-input>
        </div>
        <div class="content-right">
          <el-button type="primary" @click="search_btn" :disabled="userName == ''">搜索</el-button>
          <el-button type="info" @click="reset_btn">重置</el-button>
        </div>
      </div>
    </el-card>
    <!-- 下半部分 -->
    <el-card class="box-card" style="margin:15px 0;">
      <el-button type="primary" @click="addUser">添加</el-button>
      <el-button type="danger" @click="batchDelete" :disabled="deleteUserIdList.length == 0">批量删除</el-button>
      <el-table :data="userInfo" border @selection-change="selectHanlder" style="margin:10px 0;">
        <el-table-column type="selection" width="60"></el-table-column>
        <el-table-column label="#" type="index" width="60"></el-table-column>
        <el-table-column prop="id" label="id" width="80"></el-table-column>
        <el-table-column prop="name" label="用户名字" width="100" show-overflow-tooltip></el-table-column>
        <el-table-column prop="username" label="用户名称" width="100" show-overflow-tooltip></el-table-column>
        <el-table-column prop="roleName" label="用户角色" width="100" show-overflow-tooltip></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" show-overflow-tooltip></el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="180" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作">
          <template #="{row,$index}">
            <el-button type="primary" size="small" icon="User" @click="distributeRole_btn(row)">分配角色</el-button>
            <el-button type="primary" size="small" icon="edit" @click="edit_btn(row)">编辑</el-button>          
            <el-popconfirm :title="`确定要删除${row.name}吗?`" @confirm="del_btn(row)">
              <template #reference>
                <el-button type="primary" size="small" icon="delete">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination :current-page="paging.pageNo" :page-size="paging.pageSize" :total="paging.total" background layout="prev, pager, next, jumper, ->, sizes, total" :page-sizes="[3,5,7,9,20]" @current-change="handlerCurrent" @size-change="handlerSize" />
    </el-card>
    <!-- 添加用户或者修改用户的弹出框组件 -->
    <el-drawer v-model="drawerOnOrOff" :title="newUser.id == undefined?'添加用户':'修改用户'" @close="cancel_btn">
      <template #default>
        <el-form label-width="80px" :model="newUser" >
          <el-form-item label="用户姓名">
            <el-input v-model="newUser.name" autofocus/>
          </el-form-item>
          <el-form-item label="用户昵称">
            <el-input v-model="newUser.username" />
          </el-form-item>
          <el-form-item v-if="!newUser.id" label="用户密码">
            <el-input v-model="newUser.password" />
          </el-form-item>
        </el-form>
      </template>
      <!-- 底部按钮部分 -->
      <template #footer>
        <div style="flex: auto">
          <el-button @click="cancel_btn">取消</el-button>
          <el-button type="primary" @click="confirm_btn">确定</el-button>
        </div>
      </template>
    </el-drawer>
    <!-- 分配角色的drawer弹出框 -->
    <el-drawer v-model="distributeRole_drawerOnOrOff" title="分配用户角色">
      <el-form label-width="80px">
        <el-form-item label="用户姓名">
          <el-input v-model="distributeRole.name" disabled/>
        </el-form-item>
        <el-form-item label="角色列表">
          <el-checkbox v-model="distributeRole.checkAll" :indeterminate="distributeRole.isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
          <el-checkbox-group v-model="distributeRole.checkedRole" @change="handleCheckedCitiesChange">
            <el-checkbox v-for="item,index in distributeRole.allRole" :key="index" :label="item">{{item.roleName}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <!-- 底部按钮部分 -->
      <template #footer>
        <div style="flex: auto">
          <el-button @click="ditributeRole_cancel_btn">取消</el-button>
          <el-button type="primary" @click="ditributeRole_confirm_btn">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ElCard, ElInput, ElButton, ElTable, ElTableColumn, ElPagination, ElMessage, ElDrawer, ElForm, ElFormItem, ElCheckbox, ElCheckboxGroup, ElPopconfirm } from "element-plus";
import { User } from '@element-plus/icons-vue';
//@ts-ignore,引入请求函数
import { reqUserList, reqAddUser, reqUpdateUser, reqDeleteUser, reqRoleListByUserId, reqDistributeRoleByUserId, reqDeleteUserList } from "@/api/permission/index.ts";
//@ts-ignore,引入类型约束
import { userInfo, response_userInfoList } from "@/api/permission/type.ts";
import { onMounted, reactive, ref } from "vue";

//用户管理相关数据
let userInfo:userInfo = ref([]);
//搜索框用户名收集input框
let userName = ref<string>("");

//分页器相关属性
let paging = reactive<any>({
  pageNo:1,
  pageSize:3,
  total:0
})
//抽屉的开关与否：添加用户
let drawerOnOrOff = ref(false);
//为用户分配角色的drawer:分配据说
let distributeRole_drawerOnOrOff = ref(false);
//添加用户的用户信息收集或者修改用户信息收集
let newUser = reactive<any>({
  name:"",
  username:"",
  password:""
})
//分配用户角色相关信息收集
let distributeRole = reactive({
  name:"",
  id:0,
  checkAll:false,
  isIndeterminate:true,
  checkedRole:[],  //已分配角色
  allRole:[]  //所有角色
})

//批量删除管理用户组成的id数组
let deleteUserIdList = ref([]);

//生命周期
onMounted(()=>{
  //调用请求函数
  getUserList();
})

//获取全部用户
const getUserList = async () => {
  let res:response_userInfoList = await reqUserList(paging.pageNo,paging.pageSize);
  if(res.code == 200){
    userInfo.value = res.data.records;
    paging.total = res.data.total;
    ElMessage({type:"success",message:"用户数据获取成功!"});
    // console.log("用户列表api成功",res);
  }
}

//为用户分配角色的drawer中相关回调函数
//全选回调handler事件
const handleCheckAllChange = (val: boolean) => {
  distributeRole.checkedRole = val ? distributeRole.allRole : [];
  distributeRole.isIndeterminate = false;
}
//复选框组的change事件
const handleCheckedCitiesChange = (value: string[]) => {
  const checkedCount = value.length;
  distributeRole.checkAll = checkedCount === distributeRole.allRole.length;
  distributeRole.isIndeterminate = checkedCount > 0 && checkedCount < distributeRole.allRole.length;
}
//为用户分配角色drawer抽屉中底部的取消与确定按钮
const ditributeRole_cancel_btn = () => {
  //关闭drawer分配角色抽屉
  distributeRole_drawerOnOrOff.value = false;
  //清空数据
  distributeRole.name = "";
  distributeRole.id = 0;
  distributeRole.checkedRole = [];
}
const ditributeRole_confirm_btn = async () => {
  //请求参数整理
  let arr = [];
  for(let i=0; i<distributeRole.checkedRole.length; i++){
    arr.push(distributeRole.checkedRole[i].id);
  }
  //发请求，存储用户新角色信息
  let res:any = await reqDistributeRoleByUserId(distributeRole.id,arr);
  if(res.code == 200){
    ElMessage({type:"success",message:"管理用户角色分配成功!"});
    //调用关闭按钮
    ditributeRole_cancel_btn();
    //发请求，获取用户信息列表最新数据
    getUserList();
    // console.log("角色分配api成功",res);
  }
}

//添加用户或者修改用户信息的drawer中的确定与取消按钮
const confirm_btn = async() => {
  if(newUser.id){
    //修改用户
    let res:any = await reqUpdateUser(newUser);
    if(res.code == 200){
      //更新管理用户列表信息
      getUserList();
      ElMessage({type:"success",message:"管理用户更新成功!"});
      // console.log("管理用户更新api成功",res);
    }
  } else {
    //添加用户
    let res:any = await reqAddUser(newUser);
    if(res.code == 200){
      //更新管理用户列表信息
      getUserList();
      ElMessage({type:"success",message:"管理用户添加成功!"});
      // console.log("管理用户添加api成功",res);
    }
  }
  //关闭抽屉
  cancel_btn();
}
const cancel_btn = () => {
  //关闭drawer
  drawerOnOrOff.value = false;
  //清空数据
  newUser = {name:"",username:"",password:""};
}

//搜索及重置按钮
const search_btn = async () => {
  let obj = {username:userName.value};
  let res:any = await reqUserList(paging.pageNo,paging.pageSize,obj);
  if(res.code == 200){
    userInfo.value = res.data.records;
    paging.total = res.data.total;
    userName.value = "";
    ElMessage({type:"success",message:"搜索用户成功！"});
    // console.log("用户搜索成功",res);
  }
}
const reset_btn = () => {
  // //清空input框
  // userName.value = "";
  // //发请求更新用户数据
  // getUserList();
  window.location.reload();  //重新加载
}

//添加及批量删除按钮
const addUser = () => {
  //打开弹出框
  drawerOnOrOff.value = true;
}
const batchDelete = async () => {
  let res:any = await reqDeleteUserList(deleteUserIdList.value);
  if(res.code == 200){
    ElMessage({type:"success",message:"管理用户批量删除成功!"});
    //重发请求，更新用户数据
    getUserList();
    //清空待删除用户组成的数组
    deleteUserIdList.value = [];
    // console.log("批量删除管理用户api成功",res);
  }
}

//table表格中的几个功能按钮函数
const distributeRole_btn = async(row:any) => {
  //收集相关信息
  distributeRole.id = row.id;
  distributeRole.name = row.name;
  //打开drawer分配角色抽屉
  distributeRole_drawerOnOrOff.value = true;
  // console.log(row);
  //发请求获取用户角色信息
  let res:any = await reqRoleListByUserId(row.id);
  if(res.code == 200){
    distributeRole.checkedRole = res.data.assignRoles;
    distributeRole.allRole = res.data.allRolesList
  }
}
const edit_btn = (row:any) => {
  //同步信息到newUser
  newUser = row;
  //打开抽屉弹框
  drawerOnOrOff.value = true;
}
const del_btn = async (row:any) => {
  let res:any = await reqDeleteUser(row.id);
  if(res.code == 200){
    ElMessage({type:"success",message:"管理用户删除成功!"});
    // console.log("删除管理用户api成功",res);
  }
}
//表格复选框的selection-change事件
const selectHanlder = (selectUserInfo:any) => {
  // console.log(value);  //selectUserInfo值为选中的每一个item项组成的数组,element+提供
  let arr = [];
  for(let i=0; i<selectUserInfo.length; i++){
    arr.push(selectUserInfo[i].id);
  }
  deleteUserIdList.value = arr;
}

//分页器相关的回调函数
const handlerCurrent = (val:number) => {
  paging.pageNo = val;
  //重发请求
  getUserList();
}
const handlerSize = (val:number) => {
  paging.pageSize = val;
  //重发请求
  getUserList();
}

</script>
<script lang="ts">
export default {
  name:"User"
}
</script>

<style scoped lang="scss">
// 上半部分
.box-content{
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>